package com.example.service.impl;

import com.example.entity.HttpClientResult;
import com.example.service.IComicService;
import com.example.util.HttpClientUtils;
import com.example.vo.ComicInfoVo;
import com.example.vo.ComicVo;
import com.example.vo.PartVo;
import com.example.vo.SearchResultVo;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class ComicServiceImpl implements IComicService {
    @Override
    public ArrayList<SearchResultVo> search(String name) {

        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 参数
        StringBuffer params = new StringBuffer();
        try {
            // 字符数据最好encoding以下;这样一来，某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)
            params.append("kw=" + URLEncoder.encode(name, "GBK"));
            params.append("&");
            params.append("Submit=" + URLEncoder.encode("确定", "GBK"));
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        // 创建Get请求
        HttpGet httpGet = new HttpGet("https://so.kukudm.com/search.asp" + "?" + params);
        // 响应模型
        CloseableHttpResponse response = null;
        ArrayList<SearchResultVo> searchResultVoList = null;
        try {
            // 配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(5000)
                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(5000)
                    // socket读写超时时间(单位毫秒)
                    .setSocketTimeout(5000)
                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(true).build();

            // 将上面的配置信息 运用到这个Get请求里
            httpGet.setConfig(requestConfig);
            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpGet);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
//            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
//                System.out.println("响应内容长度为:" + responseEntity.getContentLength());

                String content = EntityUtils.toString(responseEntity, "GBK");
//                System.out.println("响应内容为:" + content);
                Document document = Jsoup.parse(content);

                Elements aList = document.select("#comicmain dd a:nth-child(2)");
                Elements imgList = document.select("#comicmain dd img");
                searchResultVoList = new ArrayList<>();

                for(int i = 0; i < imgList.size(); i++){
                    SearchResultVo vo = new SearchResultVo();
                    vo.setImgUrl(imgList.get(i).attr("src"));
                    vo.setName(aList.get(i).text());
                    String url = aList.get(i).attr("href");
                    vo.setUrl(url);
                    String[] a = url.split("/");
                    String comicId = a[a.length - 1];
                    vo.setComicId(comicId);
                    searchResultVoList.add(vo);
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return searchResultVoList;
    }

    @Override
    public ComicInfoVo getParts(String comicId) {

        String domin = "http://comic2.kukudm.com/";

        String targetUrl = domin + "/comiclist/" + comicId;
        ComicInfoVo comicInfoVo = null;
        try {
            HttpClientResult result = HttpClientUtils.doGet(targetUrl);
            Document document = Jsoup.parse(result.getContent());
            Elements info = document.select("table[cellpadding=\"7\"] tr");

            String name = info.get(0).child(0).text();
            String imgUrl = info.get(1).child(0).child(0).attr("src");
            String intro = info.get(2).child(0).child(1).text();
            String str = info.get(4).child(0).text();
            String[] s = str.split(" \\| ");
            String author = s[0].split("：")[1];
            String status = s[1].split("：")[1];
            String updateDate = s[2].split("：")[1];

            Elements ddList = info.get(5).select("dd");
            List<PartVo> partVos = new ArrayList<>();
            for(Element dd : ddList){
                Element a = dd.child(0);
                String href = a.attr("href");
                String partName = a.text();
                String[] s1 = href.split("/");
                String partId = s1[s1.length - 2];
                partVos.add(new PartVo(partId,partName));
            }
            comicInfoVo = new ComicInfoVo(comicId, name, imgUrl, intro, author, status, updateDate, partVos);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return comicInfoVo;
    }

    @Override
    public List<String> getPart(String comicId, String partId){

        String domin = "http://comic2.kukudm.com/";
        String picDomin = "http://v2.kukudm.com/";
        CloseableHttpClient httpClient = HttpClients.createDefault();

        String firstTargetUrl = domin + "/comiclist/" + comicId + "/" + partId + "/" + "1.htm";
        List<String> picList = new ArrayList<>();
        HttpClientResult firstResult = null;
        try {
            firstResult = HttpClientUtils.doGet(httpClient,firstTargetUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String firstContent = firstResult.getContent();
        String totalPageRegex = "\\| 共(\\d+)页 \\|*";
        Pattern pattern = Pattern.compile(totalPageRegex);
        Matcher matcher = pattern.matcher(firstContent);
        int totalPage = 0;
        if (matcher.find()){
            totalPage = Integer.parseInt(matcher.group(1));
        }

        String srcRegex = "<IMG srC='\"+(.*?)+\"(.*?)'>";
        Pattern pattern1 = Pattern.compile(srcRegex);
        Matcher matcher1 = pattern1.matcher(firstContent);
        String firstSrc = "";
        if (matcher1.find()){
            firstSrc = picDomin + matcher1.group(2);
        }
        picList.add(firstSrc);

        for(int i = 2; i <= totalPage; i++){
            String targetUrl = domin + "/comiclist/" + comicId + "/" + partId + "/" + i +".htm";
            HttpClientResult result = null;
            try {
                result = HttpClientUtils.doGet(httpClient, targetUrl);
            } catch (Exception e) {
                e.printStackTrace();
            }
            Matcher matcher2 = pattern1.matcher(result.getContent());
            String src = "";
            if (matcher2.find()){
                src = picDomin + matcher2.group(2);
            }
            picList.add(src);
        }
        try {
            HttpClientUtils.release(null,httpClient);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return picList;
    }
}
